package com.cat.orm.core.convert;

import com.cat.orm.core.base.ICommonData;
import com.cat.orm.core.base.SimpleBasePo;
import com.cat.orm.util.SimpleJsonUtil;

/**
 * 简单的json序列化器
 * @author Jeremy Feng
 * @date 2024/10/19 23:19
 */
public final class SimpleDataJsonConvert<D extends ICommonData> extends AbstractDataConverter<D, SimpleBasePo>{

    public SimpleDataJsonConvert(Class<D> dataClazz) {
        super();
        this.baseDataClazz = dataClazz;
    }

    private D fromBytes(long id, byte[] bytes) throws Exception {
        D data = SimpleJsonUtil.toObject(bytes, baseDataClazz);
        data.setId(id);
        return data;
    }

    private byte[] toBytes(D data) {
        return SimpleJsonUtil.toJsonBytes(data);
    }

    @Override
    public Object getKey(D data) {
        return data.getId();
    }

    @Override
    public SimpleBasePo data2Po(D data) {
        SimpleBasePo basePo = new SimpleBasePo();
        basePo.setId(data.getId());
        byte[] bytes = this.toBytes(data);
        basePo.setData(bytes);
        return basePo;
    }

    @Override
    public D po2Data(SimpleBasePo pojo) throws Exception {
        long id = pojo.getId();
        byte[] bytes = pojo.getData();
        D data = this.fromBytes(id, bytes);
        return data;
    }

    @Override
    public Class<D> getDataClazz() {
        return baseDataClazz;
    }

    @Override
    public Class<SimpleBasePo> getPojoClazz() {
        return SimpleBasePo.class;
    }


}
